package transaction

import (
	"context"
	"fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetTransactionListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetTransactionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTransactionListLogic {
	return &GetTransactionListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetTransactionListLogic) GetTransactionList(in *user.BaseListReq) (*user.TransactionListResp, error) {
	logrus.Info(fmt.Sprintf("GetTransactionList BaseListReq: %+v", in))
	// 

	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)

	logrus.Info(fmt.Sprintf("GetTransactionList preloadMap: %+v", preloadMap))
	// 
	logrus.Info(fmt.Sprintf("GetTransactionList eagerLoadMap: %+v", eagerLoadMap))
	// 

	transactionEntityName := model.RpcEntityNames.Transaction
	_, hasSettingMap := model.RpcEntityPreloadMap[transactionEntityName]
	if !hasSettingMap {
		return &user.TransactionListResp{}, nil
	}

	transactionRepositoryName := model.RepositoryNames.Transaction
	columnMap, hasColumnMap := model.RepositoryPreloadMap[transactionRepositoryName]
	if !hasColumnMap {
		return &user.TransactionListResp{}, nil
	}

	var selectCols []string
	if preloadFields, hasPreloadFields := preloadMap[transactionEntityName]; hasPreloadFields {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	logrus.Info(fmt.Sprintf("GetTransactionList filterMap: %+v", filterMap))
	// 
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	filterMap[model.UserTransactionLogColumns.Status] = map[string][]any{
		"equalTo": []any{globalkey.StatusEnabled},
	}
	if in.VisitorId != nil && *in.VisitorId > 0 {
		filterMap[model.UserTransactionLogColumns.UserID] = map[string][]any{
			"equalTo": []any{*in.VisitorId},
		}
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	logrus.Info(fmt.Sprintf("GetTransactionList orderBy: %s", orderBy))
	// 

	if len(orderBy) == 0 {
		orderBy = model.UserTransactionLogColumns.UserTransactionLogID + " DESC"
	}
	res, count, err := l.svcCtx.CurrentUser.GetTransactionLogList(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		// "search":  in.Search,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, err
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &user.TransactionListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	if len(res) > 0 {
		// subRpcEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
		if eagerLoadEntities, hasEagerLoadEntities := eagerLoadMap[transactionEntityName]; hasEagerLoadEntities {
			for _, entity := range eagerLoadEntities {
				if entity == "total" {
					_, total, err := l.svcCtx.CurrentUser.GetTransactionLogList(l.ctx, model.M{}, 0, filterMap)
					if err != nil {
						logx.Errorw("GetTransactionList total err", logx.Field("detail", err.Error()))
					} else {
						resp.Total = uint64(total)
					}
				}
			}
		}

		for _, v := range res {
			resp.List = append(resp.List, &user.TransactionInfo{
				Id:           &v.UserTransactionLogID,
				UserId:       &v.UserID,
				UserName:     &v.UserName,
				AssetType:    pointy.GetPointer(uint32(v.AssetType)),
				ChangeType:   pointy.GetPointer(uint32(v.ChangeType)),
				ChangeAmount: &v.ChangeAmount,
				SourceType:   pointy.GetPointer(uint32(v.SourceType)),
				SourceId:     &v.SourceID,
				SourceDesc:   &v.Desc,
				Status:       pointy.GetPointer(uint32(v.Status)),
				CreatedAt:    pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:    pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			})
		}
	}

	return resp, nil
}
